//
//  UIViewController+Navi.swift
//  CommonTools
//
//  Created by xianquan on 2024/2/27.
//

import TYUIKit





extension UIViewController {
    @objc open func leftAction(sender: UIButton){
        if (navigationController?.viewControllers.count ?? 0 > 1) {
            navigationController?.popViewController(animated: true)
        }
        else{
            dismiss(animated: true)
        }
    }
    @objc open func rightAction(_ sender: UIButton){}
    
    @objc open func setTitle(_ title: String, rightTitle: String? = nil){
        guard let navigationController = navigationController else {return}
        navigationItem.title = title
        
        if navigationController.viewControllers.count > 1 || presentingViewController != nil {
            let backBtn = UIButton()
            backBtn.frame = CGRectMake(0, 0, 40, 44)
            backBtn.setImage(.imageIn(bundleName: .commonTools("app_back_black"), originSize: CGSize(width: 24, height: 24)), for: .normal)
            backBtn.addTarget(self, action: #selector(leftAction(sender:)), for: .touchUpInside)
            backBtn.contentHorizontalAlignment = .left
            let backItem = UIBarButtonItem(customView: backBtn)
            self.navigationItem.leftBarButtonItem = backItem;
        }
        guard let rightTitle = rightTitle else {return}
        let rightBar = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 30))
        
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: rightBar.height))
        
        btn.setTitle(rightTitle, for: .normal)
        btn.setBackgroundColor(.clear, for: .normal)
        btn.setTitleColor(TY_RGBAColor(38, 36, 53, 1), for: .normal)
        btn.setTitleColor(TY_RGBAColor(38, 36, 53, 0.7), for: .highlighted)
        btn.setTitleColor(TY_RGBAColor(38, 36, 53, 0.5), for: .disabled)

        btn.titleLabel?.font = adapt(15).regular
        let width = rightTitle.width(for: adapt(15).regular)
        if (width > 30.0){
            btn.ty_width = width;
        }
        btn.addTarget(self, action: #selector(rightAction), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
    }
}
